package com.olympus.hermes.auth.service;

import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.client.BaseClientDetails;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mickey
 * @since 2020.08.13
 */
@Service
public class ClientService implements ClientDetailsService {

    private final Map<String, BaseClientDetails> clientMap;

    public ClientService(PasswordEncoder passwordEncoder) {
        this.clientMap = new HashMap<>();
        BaseClientDetails clientDetails = new BaseClientDetails();
        clientDetails.setClientId("iOS");
        clientDetails.setAuthorizedGrantTypes(Arrays.asList("password", "sms_code", "client_credentials", "wechat_applet"));
        clientDetails.setAccessTokenValiditySeconds(3 * 60 * 60 * 24);
        clientDetails.setRefreshTokenValiditySeconds(3 * 60 * 60 * 24);
        clientDetails.setClientSecret(passwordEncoder.encode("admin123456"));
        clientDetails.setScope(Collections.singletonList("all"));
        clientMap.put(clientDetails.getClientId(), clientDetails);

        BaseClientDetails baseClientDetails = new BaseClientDetails();
        baseClientDetails.setClientId("befdm3vwtpt6topp");
        baseClientDetails.setAuthorizedGrantTypes(Arrays.asList("password", "client_credentials", "wechat_applet"));
        baseClientDetails.setAccessTokenValiditySeconds(30);
        baseClientDetails.setRefreshTokenValiditySeconds(3 * 60 * 60 * 24);
        baseClientDetails.setClientSecret(passwordEncoder.encode("xi2iczr4zd3wf7lrle"));
        baseClientDetails.setScope(Collections.singletonList("all"));
        clientMap.put(baseClientDetails.getClientId(), baseClientDetails);
    }

    @Override
    public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
        return clientMap.get(clientId);
    }
}
